// SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
// SPDX-License-Identifier: GPL-3.0-only

package image_cmd

import (
	"fmt"
	"strings"

	"gitcode.com/openseaotter/so_proto_gen_go.git/image_api"
	"gitcode.com/openseaotter/so_server/config"
	"gitcode.com/openseaotter/so_server/utils"
	"github.com/spf13/cobra"
)

var listImageTagCmd_Offset uint32
var listImageTagCmd_Limit uint32

var listImageTagCmd = &cobra.Command{
	Use: "listImageTag",
	PreRunE: func(cmd *cobra.Command, args []string) error {
		if len(args) != 2 {
			return fmt.Errorf("need param [group name] [image name]")
		}
		return nil
	},
	RunE: func(cmd *cobra.Command, args []string) error {
		cfg, err := config.ReadServerConfig()
		if err != nil {
			return err
		}
		if cfg.SuperToken == "" {
			return fmt.Errorf("miss super token in config")
		}
		conn, err := utils.ConnGrpcServer(fmt.Sprintf("127.0.0.1:%d", cfg.ServicePort))
		if err != nil {
			return err
		}
		defer conn.Close()

		client := image_api.NewImageApiClient(conn)

		groupName := args[0]
		imageName := args[1]

		res, err := client.ListReference(cmd.Context(), &image_api.ListReferenceRequest{
			AccessToken:  cfg.SuperToken,
			GroupName:    groupName,
			ImageName:    imageName,
			LoadManifest: true,
			Offset:       listImageTagCmd_Offset,
			Limit:        listImageTagCmd_Limit,
		})
		if err != nil {
			return err
		}
		if res.Code != image_api.ListReferenceResponse_CODE_OK {
			return fmt.Errorf("%s", res.ErrMsg)
		}
		fmt.Println("image tag count", res.TotalCount)
		for _, refItem := range res.ReferenceList {
			platformList := []string{}
			for _, manifest := range refItem.ManifestInfo.Manifests {
				platformList = append(platformList, fmt.Sprintf("%s_%s", manifest.Architecture, manifest.Os))
			}
			fmt.Printf("%s %s platform:%s\n", refItem.Reference, refItem.Digest, strings.Join(platformList, ","))
		}
		return nil
	},
}

func init() {
	listImageTagCmd.Flags().Uint32Var(&listImageTagCmd_Offset, "offset", 0, "list offset")
	listImageTagCmd.Flags().Uint32Var(&listImageTagCmd_Limit, "limit", 10, "list limit")
}
